/**
 * 394. 字符串解码
 * https://leetcode-cn.com/problems/decode-string/
 */

let i;

/**
 * @param {string} s
 * @return {string}
 */
function decodeSub(s) {
  let result = '';
  while (i < s.length) {
    const char = s[i];
    if (char === ']') {
      i += 1;
      return result;
    }
    if (char >= 'a' && char <= 'z') {
      const begin = i;
      i += 1;
      while (i < s.length && s[i] >= 'a' && s[i] <= 'z') {
        i += 1;
      }
      result += s.substring(begin, i);
    } else {
      const begin = i;
      i += 1;
      while (s[i] !== '[') {
        i += 1;
      }
      let count = parseInt(s.substring(begin, i), 10);
      i += 1;
      const substr = decodeSub(s);
      while (count) {
        result += substr;
        count -= 1;
      }
    }
  }
  return result;
}

/**
 * @param {string} s
 * @return {string}
 */
function decodeString(s) {
  i = 0;
  return decodeSub(s);
}

console.log(decodeString('3[a]2[bc]') === 'aaabcbc');
console.log(decodeString('3[a2[c]]') === 'accaccacc');
console.log(decodeString('2[abc]3[cd]ef') === 'abcabccdcdcdef');
console.log(decodeString('abc3[cd]xyz') === 'abccdcdcdxyz');
console.log(decodeString('abc') === 'abc');
